//
//  SYSearchJumpViewController.m
//  TermOfSectionB
//
//  Created by dlios on 15/12/2.
//  Copyright © 2015年 韩震明. All rights reserved.
//

#import "SYSearchJumpViewController.h"
#import "SYSearchJumpCollectionViewCell.h"
#import "SYSearchJumpCollectionViewModel.h"
//#import "SYShoppingViewController.h"

@interface SYSearchJumpViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, strong) UICollectionView *mainCollectionView;
@property (nonatomic, strong) NSMutableArray *mainArray;
@property (nonatomic, assign) NSInteger page;

@end

@implementation SYSearchJumpViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self createMainCollectionView];
    
    [self createMainCollectionViewData];
}

// 创建CollectionView
- (void)createMainCollectionView {
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(150, 200);
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 15, 5, 10);
    
    self.mainCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) collectionViewLayout:flowLayout];
    [self.view addSubview:self.mainCollectionView];
    [self.mainCollectionView registerClass:[SYSearchJumpCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    self.mainCollectionView.dataSource = self;
    self.mainCollectionView.delegate = self;
}

// collectionView数据解析
- (void)createMainCollectionViewData {
    NSString *str = @"http://api.xiangqu.com/search/list";
    NSURL *url = [NSURL URLWithString:str];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"post"];
    NSString *bodyStr = [NSString stringWithFormat:@"fromType=-1&imageHD=2&key=c180a988bc3d83cdf9a98953113fdd86&keyword=%@&page=0&t=1446295265858&userid=705811&version=3.5.4", self.string];
    NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:bodyData];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        
        self.mainArray = [NSMutableArray array];
        self.mainArray = [SYSearchJumpCollectionViewModel baseModelByArr:dic[@"data"][@"records"]];
        
        if (self.mainArray.count == 0) {
            UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"对不起" message:@"您搜索的商品不存在" preferredStyle:UIAlertControllerStyleAlert];
            [self presentViewController:alertC animated:YES completion:nil];
            
            UIAlertAction *leftAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                [self.navigationController popViewControllerAnimated:YES];
            }];
            
            UIAlertAction *rightAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
            [alertC addAction:leftAction];
            [alertC addAction:rightAction];
        }
        
        [self.mainCollectionView reloadData];
        
    }];
}

// 根据数据解析的情况,返回数组中数据解析出来数据的个数.
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.mainArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    SYSearchJumpCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    SYSearchJumpCollectionViewModel *model = self.mainArray[indexPath.row];
    
    [cell.productImage sd_setImageWithURL:[NSURL URLWithString:model.image]];
    cell.titleLabel.text = model.brand;
    cell.titleLabel.textColor = [UIColor whiteColor];
    cell.contetLabel.text = model.productDescription;
    
    // 关键字高亮
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:cell.contetLabel.text];
    NSRange range = [cell.contetLabel.text rangeOfString:self.searchText];
    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
    cell.contetLabel.attributedText = attributedString;
    
    return cell;
}

- (void)viewWillAppear:(BOOL)animated {
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    self.tabBarController.tabBar.hidden = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
